#!/usr/bin/env python
# coding=utf-8
# @FileName  :note_img.py
# @Time      :2024/6/17 20:59
# @Author    :jdz
import os
import re
import shutil
from tqdm import tqdm

# ======================================
# = config =
obsidianVault = r'D:\Notes\Obsidian\code\Java'
accessoryPath = 'assets'
imagesPath = 'D:/Notes/Typora/Pic'
# ======================================


imagesList = os.listdir(imagesPath)


def list_dir_in_folder(folderPath):
    resList = []
    folderList = os.listdir(folderPath)
    folderList = [os.path.join(folderPath, v) for v in folderList]
    for folder in folderList:
        if os.path.isdir(folder):
            resList.append(os.path.join(folderPath, folder))

    return resList


folderList = [obsidianVault]


def operate_in_folder(folderPath):
    print('=' * 64)
    print(f'cd {folderPath}')
    # 栈操作: 2.将对执行图片迁移操作的父文件夹中的子文件夹path加入栈中
    global folderList
    folderList.extend(list_dir_in_folder(folderPath))

    files = []
    for fileName in os.listdir(folderPath):
        if fileName[-3:] == '.md':
            filePath = os.path.join(folderPath, fileName)
            files.append(filePath)

    if not files:
        return

    for filePath in files:
        with open(filePath, 'r', encoding='utf-8') as f:
            content = f.read()
            pattern = r'!\[\[(.*?)]\]'  # 匹配 [[...]] 格式的内容
            imgs = re.findall(pattern, content)

        # 仅对含有图片的文档创建附件夹并移动相应的图片
        if imgs:
            fileName = os.path.basename(filePath)
            attPath = os.path.join(folderPath, accessoryPath, fileName[:-3])
            if not os.path.exists(attPath):
                os.makedirs(attPath)
            print(f'File: [{fileName}]. Attachments path: [{attPath}]. Total: [{len(imgs)}]')

            for img in tqdm(imgs):
                if img not in imagesList:
                    print(f'[WARNING]: {img} could not be found and will skip moving.')
                    continue
                srcPath = os.path.join(imagesPath, img)
                dstPath = os.path.join(attPath, img)
                # 如果已经存在，就不移动，针对md文档中的一张图片被多次引用的情况
                if not os.path.exists(dstPath):
                    shutil.move(srcPath, dstPath)

                imgLink = os.path.join(accessoryPath, fileName[:-3], img).replace('\\', '/').replace(' ', '%20')
                content = content.replace(f'![[{img}]]', f'![]({imgLink})')

            with open(filePath, 'w', encoding='utf-8') as f:
                f.write(content)

    print('-' * 64)


while folderList:
    # 栈操作: 1.删除栈中的索引文件夹path
    operate_in_folder(folderList.pop())
print('\n\n[DONE]: Please check.')
